<template>
  <div class="status-distribution-container">
    <h2>资产状态分布</h2>
    <div class="charts-container">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>饼图展示</span>
          </div>
        </template>
        <div id="statusPieChart" class="chart"></div>
      </el-card>
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>柱状图展示</span>
          </div>
        </template>
        <div id="statusBarChart" class="chart"></div>
      </el-card>
    </div>
    
    <el-card class="data-table-card">
      <template #header>
        <div class="card-header">
          <span>详细数据</span>
        </div>
      </template>
      <el-table :data="statusData" style="width: 100%">
        <el-table-column prop="name" label="状态" width="180"></el-table-column>
        <el-table-column prop="value" label="数量" width="180"></el-table-column>
        <el-table-column prop="percentage" label="占比" width="180">
          <template #default="scope">
            {{ scope.row.percentage || 0 }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'

export default {
  name: 'StatusDistribution',
  setup() {
    const statusData = ref([])
    let statusPieChart = null
    let statusBarChart = null

    // 获取状态分布数据
    const getStatusDistribution = async () => {
      try {
        const response = await axios.get('/api/statistics/status-distribution')
        if (response.code === 200 && response.data) {
          const data = response.data
          calculatePercentage(data)
          statusData.value = data
          initStatusPieChart(data)
          initStatusBarChart(data)
        } else {
          // 使用模拟数据
          const mockData = [
            { name: '在用', value: 850 },
            { name: '闲置', value: 230 },
            { name: '维修', value: 80 },
            { name: '报废', value: 74 }
          ]
          calculatePercentage(mockData)
          statusData.value = mockData
          initStatusPieChart(mockData)
          initStatusBarChart(mockData)
        }
      } catch (error) {
        console.error('获取状态分布数据失败:', error)
        // 使用模拟数据
        const mockData = [
          { name: '在用', value: 850 },
          { name: '闲置', value: 230 },
          { name: '维修', value: 80 },
          { name: '报废', value: 74 }
        ]
        calculatePercentage(mockData)
        statusData.value = mockData
        initStatusPieChart(mockData)
        initStatusBarChart(mockData)
      }
    }

    // 计算百分比
    const calculatePercentage = (data) => {
      const total = data.reduce((sum, item) => sum + item.value, 0)
      data.forEach(item => {
        item.percentage = ((item.value / total) * 100).toFixed(2)
      })
    }

    // 初始化饼图
    const initStatusPieChart = (data) => {
      if (statusPieChart) {
        statusPieChart.dispose()
      }
      statusPieChart = echarts.init(document.getElementById('statusPieChart'))
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '资产状态',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ]
      }
      statusPieChart.setOption(option)
    }

    // 初始化柱状图
    const initStatusBarChart = (data) => {
      if (statusBarChart) {
        statusBarChart.dispose()
      }
      statusBarChart = echarts.init(document.getElementById('statusBarChart'))
      const names = data.map(item => item.name)
      const values = data.map(item => item.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: names
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '资产数量',
            type: 'bar',
            data: values,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      }
      statusBarChart.setOption(option)
    }

    // 监听窗口大小变化
    const handleResize = () => {
      if (statusPieChart) {
        statusPieChart.resize()
      }
      if (statusBarChart) {
        statusBarChart.resize()
      }
    }

    onMounted(() => {
      getStatusDistribution()
      window.addEventListener('resize', handleResize)
    })

    onBeforeUnmount(() => {
      if (statusPieChart) {
        statusPieChart.dispose()
      }
      if (statusBarChart) {
        statusBarChart.dispose()
      }
      window.removeEventListener('resize', handleResize)
    })

    return {
      statusData
    }
  }
}
</script>

<style scoped>
.status-distribution-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 340px;
}

.data-table-card {
  margin-top: 20px;
}
</style>